<?php
/**
 * Created by PhpStorm.
 * AdminUser: Administrator
 * Date: 2020/11/24
 * Time: 17:00
 */
namespace app\common\model;

use think\facade\Cookie;
use think\facade\Session;
use think\Model;

class User extends Model
{
    protected $createTime = 'add_time';

    /**
     * 获得当前用户的企业id, 或者通过用户id取得company_id
     * @param int $user_id 用户id
     * @return int
     */
    public static function get_user_company_id($user_id = 0)
    {
        if (!$user_id) {
            $user_id = self::get_user_id();
        }

        return _uri('user', ['id'=>$user_id], 'company_id');
    }

    /**
     * 获取当前登录的用户id
     * @return int
     */
    public static function get_user_id()
    {
        static $static_get_user_id = NULL;
        if ($static_get_user_id === NULL) {
            if (isset($_SESSION['user_id'])) {
                $static_get_user_id = $_SESSION['user_id'];
            } else {
                $static_get_user_id = 0;
            }
        }

        if ($static_get_user_id == 0 && !is_weixin() && ONDEV) {
            // if ($static_get_user_id == 0 && ONDEV) {
            $static_get_user_id = 100029;
        }

        return $static_get_user_id;
    }

    /**
     * 随机产生A-Z, a-z, 0-9的字符串
     * @param int $length 随机数的长度
     * @return string
     */
    public static function random_hash($length = 4)
    {
        $salt = array_merge(range('A', 'Z'), range('a', 'z'), range(0, 9));
        $count = count($salt);
        $hash = '';
        for ($i = 0; $i < $length; $i++) {
            $hash .= $salt[mt_rand(0, $count-1)];
        }
        return $hash;
    }

    /**
     * 设置加'盐'密码
     * @param string 用户密码
     * @param $hash 用户hash
     * @return 返回接好的密码
     */
    public static function set_pwd($password, $hash)
    {
        //return md5($password.$hash);

        $savepassword = md5(sha1( $password.$hash, true ).$hash);
        return $savepassword;
    }

    /**
     * 更新 access_token
     * @param unknown $user_id
     * @return boolean
     */
    public static function update_access_token($user_id)
    {
        if (empty($user_id)) {
            return '';
        }

        $user_info = _uri('user', ['id'=>$user_id]);
        if (empty($user_info)) {
            return '';
        }

        $update = array();
        $hash   = self::random_hash();
        $update['token'] = self::set_pwd($user_info["id"], $hash);

        //_model('user')->update($user_info['id'], $update);

        $where = ['id' => $user_info['id']];
        //$this->where($where)->save($update);
        User::update($update,$where);

        return $update['token'];
    }

    /**
     * 设置用户的永久登录状态
     * @param array $info 用户信息数组（必须含id和hash键）
     */
    public static function remember_me_set($user_info)
    {
        $id_hash = $user_info['id'].config('cookie.cookie_delimiter').$user_info['hash'];

//        $genpass = convert_uuencode(gen_pass($id_hash));
        $genpass = convert_uuencode($id_hash);

//        Cookie::set_path(config('cookie.path'));
//        Cookie::set_domain(config('cookie.domain'));

        // 永久登录默认为一年，如需要多种，可以设置为变量
        cookie('remember_me', $genpass, time()+3600*24*365);
        //记录公司域名
        cookie('remember_corporation', $user_info['corporation_id'], time()+3600*24*365);
        // 更新session状态
        self::session_update($user_info);

        return $genpass;
    }

    /**
     * 使用户的remember_me状态失效
     */
    public static function remember_me_expire()
    {
        Cookie::delete('remember_me');
        Cookie::delete('remember_corporation');
        //session('admin_id', null);
        // 删除session
        session(null);
        return TRUE;
    }

    /**
     * 更新session状态
     * @param array $info 用户信息数组
     */
    public static function session_update($info)
    {
        session('user_id', $info['id']);
        //$_SESSION['corporation_id'] = $info['corporation_id'];
        // 管理员分离admin_id
        if (static::have_privilege($info['id'])) {
            session('admin_id', $info['id']);
        } else {
            session('admin_id', 0);
        }
    }

    /**
     * 检查用户是否有进入后台的权限
     * @param $admin_id 默认为当前登录用户的admin_id
     * @return bool
     */
    public static function have_privilege($admin_id = 0)
    {
        $admin_id = (int)$admin_id;

        if (empty($admin_id)) {
            $admin_id = self::get_admin_id();
        }

        if (empty($admin_id)) {
            return FALSE;
        }

        // @FIXME 临时采用privilege来给菜单赋权限 START
        $role_ids = self::get_user_role_ids($admin_id);
        foreach ($role_ids as $v) {
            $privilege = _uri('role', ['id'=>$v], 'privilege');
            if ($privilege) {
                return TRUE;
            }
        }

        $user_info = _uri('user', array('id'=>$admin_id, 'status'=>1));
        if ($user_info && $user_info['type'] <= 10) {
            return TRUE;
        }

        return FALSE;
        // @FIXME 临时采用privilege来给菜单赋权限 END

        //    return AnAcl::hasDefinedAuth($admin_id);
    }

    /**
     * 获取当前登录的admin_id
     * @return int
     */
    public static function get_admin_id()
    {
        static $static_get_admin_id = NULL;
        if ($static_get_admin_id === NULL) {
            $static_get_admin_id = session('admin_id') ? session('admin_id') : 0;
        }
        return $static_get_admin_id;
    }

    /**
     * 获取用户所属的角色id列表
     * @param int|array $user_id 用户id或者id数组
     * @param string $order 排序以及LIMIT限制，默认所有角色id
     * @return array
     */
    public static function get_user_role_ids($user_id, $order = 'ORDER BY `add_time` DESC')
    {
        if (empty($user_id)) {
            return array();
        }

        $filter = array('user_id'=>$user_id);

        $role_ids = RoleUser::where($filter)->column('role_id');

        return array_unique($role_ids);
    }

    /**
     * 取得用户的信息，如果不传$user_id，刚取当前登陆用户
     * @param int $user_id
     * @return array
     */
    public static function get_user_info($user_id)
    {
        if (!$user_id) {
            return array();
        }

        return _uri('user', ['id'=>$user_id]);
    }

    /**
     * 按照用户空间设置的姓名显示方式显示姓名
     * 如果是管理员则显示：注册名（真实姓名）/注册名（昵称）
     * @param int $user_id
     * @return string
     * @TODO 空间自定义设置的姓名显示方式
     */
    public static function display_name($user_id)
    {
        static $static_display_name = array();
        if (!isset($static_display_name[$user_id])) {
            $static_display_name[$user_id] = '';

            $user_id = (int)$user_id;
            if ($user_id) {
                $user_info = _uri('user', $user_id);
                if ($user_info) {
                    if ($user_info['nick_name']) {
                        $static_display_name[$user_id] = $user_info['nick_name'];

                    } else if ($user_info['user_name']) {
                        $static_display_name[$user_id] = $user_info['user_name'];

                    } else if ($user_info['mobile']) {
                        $static_display_name[$user_id] = $user_info['mobile'];
                    }
                }
            }
        }

        return $static_display_name[$user_id];
    }
}